﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GeneralDFS.BusinessLogical
{
    public class Speed
    {
        private static Speed speed;
        private TimeSpan _time;
        private double _length;
        private int sendCount;
        public static Speed GetInstance()
        {
            if (speed == null)
                speed = new Speed();
            return speed;
        }
        private Speed()
        {
            _time = new TimeSpan(0,0,0,0,0);
            _length = 0;
            sendCount = 0;
        }
        public void UpdateSpeed(TimeSpan timeSpan, long numBytes)
        {
            lock (this)
            {
                _time += timeSpan;
                _length += ((double)numBytes) / (1024 * 1024);
                sendCount++;
                if(sendCount%100==0)
                    Console.WriteLine("******Speed:{0} ******",GetSpeed());
            }

        }
        /// <summary>
        /// 获得当前dataNode节点的传输速度
        /// </summary>
        /// <returns></returns>
        public double GetSpeed()
        {
            if ((int)_length==0)
            {
                return 0;
            }
            double averageSpeed = _length/_time.TotalSeconds;
            return averageSpeed;
        }
    }
}
